<script setup lang="ts">
import type { AgentAndTrainInfo, PageTableRequestData, TrainAgentInfo } from "@/common/apis/intelligent/type"
import type { AgentConfig } from "@/common/apis/train/type"
import { searchAgentAndTrainedApi } from "@/common/apis/train"
import { usePagination } from "@/common/composables/usePagination"
import { getProjectId } from "@/common/utils/cache/local-storage"
import CreateOrUpdate from "@/pages/intelligent/components/create-or-update.vue"
import { FormTypeEnum } from "@@/constants/other-keys"
import { Search } from "@element-plus/icons-vue"
import dayjs from "dayjs"
import { isEqual } from "lodash-es"

interface Props {
  visible: boolean
  selected: AgentConfig
  checkAgentInTeam: (agentId: string, camp: string, trainedAgentId?: string) => boolean
  getAgentTeam: (agentId: string, trainedAgentId?: string) => string | null
}
const props = defineProps<Props>()
const emit = defineEmits(["closeDialog", "joinTeam"])
const dialogVisible = ref<boolean>(false)
const loading = ref<boolean>(false)
const currentSelected = ref<AgentConfig>({})
const dialogVisibleUp = ref<boolean>(false)
const searchKey = ref<string>()
const tableData = ref<AgentAndTrainInfo[]>([])
const editDialogRef = ref()

const { paginationData, handleSizeChange, handleCurrentChange } = usePagination()

// 获取按钮提示文本
function getButtonTitle(agentId: string, targetTeam: string, trainedAgentId?: string) {
  const currentTeam = props.getAgentTeam(agentId, trainedAgentId)
  if (currentTeam && targetTeam == currentTeam) {
    return `已加入${currentTeam === "red" ? "红" : "蓝"}方阵营`
  }
  return `加入${targetTeam === "red" ? "红" : "蓝"}方阵营`
}
// 加入红方
function handleJoinRed(agent: AgentAndTrainInfo | TrainAgentInfo, baseAgent?: AgentAndTrainInfo) {
  if (baseAgent !== undefined) {
    if (props.checkAgentInTeam(baseAgent.agent_id, "red", agent.trained_agent_id)) {
      return
    }
  } else {
    if (props.checkAgentInTeam((agent as AgentAndTrainInfo).agent_id, "red", undefined)) {
      return
    }
  }
  agent.selectId = new Date().getTime()
  emit("joinTeam", {
    camp: "red",
    agent,
    isTrained: baseAgent != undefined,
    baseAgent
  })
  ElMessage.success(`智能体 ${agent.trained_agent_name || agent.agent_name} 已加入红方`)
}
// 处理加入蓝方
function handleJoinBlue(agent: AgentAndTrainInfo | TrainAgentInfo, baseAgent?: AgentAndTrainInfo) {
  if (baseAgent !== undefined) {
    if (props.checkAgentInTeam(baseAgent.agent_id, "blue", agent.trained_agent_id)) {
      return
    }
  } else {
    if (props.checkAgentInTeam((agent as AgentAndTrainInfo).agent_id, "blue", undefined)) {
      return
    }
  }
  agent.selectId = new Date().getTime()
  emit("joinTeam", {
    camp: "blue",
    agent,
    isTrained: baseAgent != undefined,
    baseAgent
  })
  ElMessage.success(`智能体 ${agent.trained_agent_name || agent.agent_name} 已加入蓝方`)
}
function closeDialog() {
  emit("closeDialog")
}
function showDialog() {
  dialogVisible.value = true
  currentSelected.value = { red: [], blue: [] }
}
function closeDialogUp() {
  dialogVisibleUp.value = false
  searchKey.value = undefined
  handleSearch()
}
function handleUpload() {
  dialogVisibleUp.value = true
}
function getTableData() {
  loading.value = true
  const params: PageTableRequestData = {
    size: paginationData.pageSize,
    current_page: paginationData.currentPage,
    agent_name: searchKey.value,
    project_id: getProjectId()
  }
  searchAgentAndTrainedApi(params)
    .then(({ data }) => {
      tableData.value = data.rows
      paginationData.total = data.total
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
function handleSearch() {
  paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1)
}

watch(
  () => props.visible,
  () => {
    if (props.visible) {
      showDialog()
    }
  }
)

watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })

const timeText = computed(() => (time: string) => {
  const date = dayjs(time)
  return date.isValid() ? date.format("YYYY-MM-DD") : "无"
})
</script>

<template>
  <el-drawer
    v-model="dialogVisible"
    direction="rtl"
    size="900px"
    @close-auto-focus="closeDialog"
    @close="closeDialog"
    :show-close="false"
    :append-to-body="true"
  >
    <template #header>
      <div class="drawer-header">
        <h4>选择智能体</h4>
      </div>
    </template>
    <template #default>
      <div class="toolbar-wrapper">
        <el-button v-throttle="() => handleUpload()">
          本地上传
        </el-button>
        <el-input v-model="searchKey" placeholder="请输入智能体名称" style="width: 300px" @keyup.enter="handleSearch">
          <template #append>
            <el-button :icon="Search" v-throttle="() => handleSearch()" />
          </template>
        </el-input>
      </div>

      <div :loading="loading">
        <div class="agent-content" v-for="(item) in tableData" :key="item.agent_id">
          <div class="agent-item agent-item-main">
            <div class="agent-item-info">
              <div class="agent-item-info-top">
                <img v-if="item.agent_type === '规则智能体'" src="@@/assets/images/agent/guize.png">
                <img v-else-if="item.agent_type === '神经网络智能体'" src="@@/assets/images/agent/wangluo.png">
                <img v-else src="@@/assets/images/agent/linear.png">
                <span class="name" :title="item.agent_name">{{ item.agent_name }}</span>
                <span class="type" :title="item.agent_type">{{ item.agent_type }}</span>
              </div>
              <div class="describe" :title="item.agent_describe">
                {{ item.agent_describe }}
              </div>
            </div>
            <div class="agent-item-operate">
              <el-tooltip
                v-if="!isEqual(item.agent_support_side, 2)"
                :content="getButtonTitle(item.agent_id, 'red', undefined)"
                placement="top"
              >
                <div class="button red" title="加入红方" v-throttle="() => handleJoinRed(item, undefined)" :class="{ disabled: checkAgentInTeam(item.agent_id, 'red', undefined) }">
                  <img src="@@/assets/images/agent/hongfang.png">
                </div>
              </el-tooltip>
              <el-tooltip
                v-if="!isEqual(item.agent_support_side, 1)"
                :content="getButtonTitle(item.agent_id, 'blue', undefined)"
                placement="top"
              >
                <div class="button blue" title="加入蓝方" v-throttle="() => handleJoinBlue(item, undefined)" :class="{ disabled: checkAgentInTeam(item.agent_id, 'blue', undefined) }">
                  <img src="@@/assets/images/agent/lanfang.png">
                </div>
              </el-tooltip>
            </div>
          </div>
          <div class="agent-item agent-item-children" v-for="(children) in item.trained_agents" :key="children.trained_agent_id">
            <div class="agent-item-info-children">
              <span class="name" :title="children.trained_agent_name">{{ children.trained_agent_name }}</span>
              <span class="version" :title="`v${children.trained_agent_version}`">v {{ children.trained_agent_version }}</span>
              <span class="reward" :title="`${children.trained_agent_reward}`">奖励值：{{ children.trained_agent_reward }}</span>
              <span class="time" :title="timeText(children.create_time)">
                {{ timeText(children.create_time) }}</span>
            </div>
            <div class="agent-item-operate">
              <el-tooltip
                v-if="!isEqual(item.agent_support_side, 2)"
                :content="getButtonTitle(item.agent_id, 'red', children.trained_agent_id)"
                placement="top"
              >
                <div class="button red" title="加入红方" v-throttle="() => handleJoinRed(children, item)" :class="{ disabled: checkAgentInTeam(item.agent_id, 'red', children.trained_agent_id) }">
                  <img src="@@/assets/images/agent/hongfang.png">
                </div>
              </el-tooltip>
              <el-tooltip
                v-if="!isEqual(item.agent_support_side, 1)"
                :content="getButtonTitle(item.agent_id, 'blue', children.trained_agent_id)"
                placement="top"
              >
                <div class="button blue" title="加入蓝方" v-throttle="() => handleJoinBlue(children, item)" :class="{ disabled: checkAgentInTeam(item.agent_id, 'blue', children.trained_agent_id) }">
                  <img src="@@/assets/images/agent/lanfang.png">
                </div>
              </el-tooltip>
            </div>
          </div>
        </div>
      </div>

      <CreateOrUpdate ref="editDialogRef" :dialog-type="FormTypeEnum.CREATE" :id="undefined" :visible="dialogVisibleUp" @close-dialog="closeDialogUp" />
    </template>
    <template #footer>
      <div class="dialog-footer-pager">
        <el-pagination
          background
          layout="total, sizes, ->, prev, pager, next, jumper"
          :disabled="loading"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :current-page="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </template>
  </el-drawer>
</template>

<style lang="scss" scoped>
@import "@@/assets/styles/mixins.scss";

.agent-content {
  padding: var(--main-padding);
  background: rgb(9, 27, 48);
  border-radius: 2px 2px 2px 2px;
  border: 1px solid #3f4c70;
}
.agent-item {
  display: flex;
  flex-direction: row;
  gap: var(--main-padding);
}
.agent-item-info {
  flex: 1;
  overflow: hidden;
  &-top {
    display: flex;
    flex-direction: row;
    align-items: center;
    gap: 10px;

    & > .name {
      max-width: 250px;
      @extend %ellipsis;
    }

    & > .type {
      max-width: 200px;
      font-size: 12px;
      color: #99a3c1;
      border: 1px solid #99a3c1;
      border-radius: 4px 4px 4px 4px;
      padding: 5px 10px;
      @extend %ellipsis;
    }
  }
  .describe {
    margin-top: 10px;
    font-size: 12px;
    color: #99a3c1;
    line-height: 22px;
    text-align: left;
    padding-right: 30px;
    @extend %ellipsis;
  }
}
.agent-item-info-children {
  flex: 1;
  overflow: hidden;
  display: flex;
  align-items: center;
  gap: var(--main-padding);
  & > .name {
    max-width: 250px;
    @extend %ellipsis;
  }

  & > .version {
    max-width: 50px;
    @extend %ellipsis;
  }

  & > .reward {
    max-width: 200px;
    font-size: 12px;
    color: #ccb6a1;
    border: 1px solid #ccb6a1;
    border-radius: 4px 4px 4px 4px;
    padding: 5px 10px;
    @extend %ellipsis;
  }

  & > .time {
    font-size: 12px;
    color: #99a3c1;
    border: 1px solid #99a3c1;
    border-radius: 4px 4px 4px 4px;
    padding: 5px 10px;
  }
}

.agent-item-operate {
  display: flex;
  flex-direction: row;
  gap: var(--main-padding);
}

.agent-content + .agent-content {
  margin-top: var(--main-padding);
}

.agent-item-toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  height: 40px;
  gap: 16px;
  .left {
    flex: 1;
    overflow: hidden;
  }

  & > div:first-child {
    justify-content: flex-start;
  }

  & > div {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 16px;
  }
}

.agent-item-children {
  margin: var(--main-padding) 0 0 26px;
  & > .agent-item-toolbar-wrapper {
    align-items: center;
    height: 40px !important;
  }
  &:not(:last-child) {
    padding-bottom: var(--main-padding);
    border-bottom: 1px solid rgba(153, 163, 193, 0.2);
  }
}

.agent-content:has(.agent-item-children) {
  .agent-item-main {
    border-bottom: 1px solid rgba(153, 163, 193, 0.2);
  }
  .describe {
    margin-bottom: var(--main-padding);
  }
}

.button {
  cursor: pointer;
}

.button.disabled {
  cursor: not-allowed;
  opacity: 0.3;
}
</style>
